package com.jy.app.lib.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.jy.app.lib.R;
import com.jy.app.lib.common.StartActivityOkResult;
import com.jy.app.lib.common.StartActivityResult;
import com.jy.app.lib.commontools.SystemStatusManager;
import com.jy.app.lib.utils.ActivityUtil;
import com.jy.app.lib.utils.LogUtil;
import com.jy.app.lib.utils.ScreenUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;

/**
 * Created by jan on 2016/4/13.
 */
public abstract class CommonActivity extends Activity{
    /**
     * 整个Activity视图的根视图
     */
    View decorView;

    /**
     * 手指按下时的坐标
     */
    float downX, downY;

    /**
     * 手机屏幕的宽度和高度
     */
    float screenWidth, screenHeight;

    private boolean isSideslipFinish = true;


    //手指向右滑动时的最小速度
    private static final int XSPEED_MIN = 200;

    //手指向右滑动时的最小距离
    private static final int XDISTANCE_MIN = 150;

    //记录手指按下时的横坐标。
    private float xDown;

    //记录手指移动时的横坐标。
    private float xMove;

    //用于计算手指滑动的速度。
    private VelocityTracker mVelocityTracker;

    private Map<Integer,StartActivityResult> startPageResultMap = new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView(int layoutResID) {
        setTheme(R.style.translucent);
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
        // 获得decorView
        decorView = getWindow().getDecorView();
        // 获得手机屏幕的宽度和高度，单位像素
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
    }

    @Override
    protected void onStart() {
        super.onStart();
        ActivityUtil.getInstance().addActivity(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityUtil.getInstance().removeActivity(this);
    }
    /**
     * 在4.4以上的设备上设置状态栏背景颜色
     * @param colorRes
     */
    protected void setTranslucentStatusColor(int colorRes,int rootViewId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
            SystemStatusManager tintManager = new SystemStatusManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(colorRes);
            View layoutAll = findViewById(rootViewId);
            if(layoutAll!=null){
                layoutAll.setPadding(0, ScreenUtils.getStatusHeight(this), 0, 0);
            }else {
                LogUtil.w("CommonActivity warn:you forgot to set rootview ID‘layout_all’ ");
            }
        }
    }

    /**
     * 在4.4以上的设备上设置状态栏背景图片
     */
    protected void setTranslucentStatusDrawable(int bgRes,int rootViewId) {
        //判断版本是4.4以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
            SystemStatusManager tintManager = new SystemStatusManager(this);
            //打开系统状态栏控制
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(bgRes);//设置背景
            View layoutAll = findViewById(rootViewId);
            //设置系统栏需要的内偏移
            if(layoutAll!=null){
                layoutAll.setPadding(0, ScreenUtils.getStatusHeight(this), 0, 0);
            }else {
                LogUtil.w("CommonActivity warn:you forgot to set rootview ID‘layout_all’ ");
            }
        }
    }

    public void setIsSideslipFinish(boolean isSideslipFinish){
        this.isSideslipFinish = isSideslipFinish;
    }
    /**
     * 通过重写该方法，对触摸事件进行处理
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isSideslipFinish)
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            downX = event.getX();
        }else if(event.getAction() == MotionEvent.ACTION_MOVE){
            if (downX>20) return true;
            float moveDistanceX = event.getX() - downX;
            if(moveDistanceX > 0){
                decorView.setX(moveDistanceX);
            }
            return super.onTouchEvent(event);
        }else if(event.getAction() == MotionEvent.ACTION_UP){
            if (downX>20) return true;
            float moveDistanceX = event.getX() - downX;
            if (moveDistanceX>0)
            if(moveDistanceX > screenWidth / 4){
                // 如果滑动的距离超过了手机屏幕的一半, 滑动处屏幕后再结束当前Activity
                continueMove(moveDistanceX);
            }else{
                // 如果滑动距离没有超过一半, 往回滑动
                rebackToLeft(moveDistanceX);
            }
        }
        return true;
    }

    /**
     * 从当前位置一直往右滑动到消失。
     * 这里使用了属性动画。
     */
    private void continueMove(float moveDistanceX){
        // 从当前位置移动到右侧。
        ValueAnimator anim = ValueAnimator.ofFloat(moveDistanceX, screenWidth);
        anim.setDuration(150); // 一秒的时间结束, 为了简单这里固定为1秒
        anim.start();

        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 位移
                float x = (float) (animation.getAnimatedValue());
                decorView.setX(x);
            }
        });

        // 动画结束时结束当前Activity
        anim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                finish();
            }

        });
    }

    /**
     * Activity被滑动到中途时，滑回去~
     */
    private void rebackToLeft(float moveDistanceX){
        ObjectAnimator.ofFloat(decorView, "X", moveDistanceX, 0).setDuration(150).start();
    }

    public void startActivityForResult(Intent intent,int requestCode,StartActivityResult result){
        startPageResultMap.put(requestCode,result);
        startActivityForResult(intent,requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (startPageResultMap.size() != 0){
            StartActivityResult pageResult = startPageResultMap.get(requestCode);
            if (pageResult!=null){
                if (pageResult instanceof StartActivityOkResult){
                    if (resultCode == RESULT_OK){
                        pageResult.onResult(requestCode,resultCode,data);
                    }
                }else{
                    pageResult.onResult(requestCode,resultCode,data);
                }
                startPageResultMap.remove(requestCode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
